from fastapi import APIRouter, Depends, HTTPException, status, Query
from fastapi.security import HTTPAuthorizationCredentials
from fastapi.responses import RedirectResponse
from typing import Optional
from datetime import datetime
from sqlalchemy.orm import Session
from sqlalchemy import or_

from database.models import User, Tools, Tools_type
from database.connection import get_db
from utils.auth import verify_password, create_user_token, get_password_hash, verify_token, security
from models.v_admin import (
    AdminLogin,
    AdminLoginResponse,
    UserCreate,
    UserUpdate,
    UserResponse,
    UserListResponse,
    SingleUserResponse,
    AdminResetPassword,
    AdminInfoUpdate,
    AdminInfoUpdateResponse
)
from models.tools import ToolsResponse
from database.models import Banner
from models.banner_models import (
    BannerCreate,
    BannerUpdate,
    BannerResponse,
    BannerListResponse,
    BannerStatusUpdate
)

# 创建管理员路由
router = APIRouter(prefix="/admin", tags=["管理员"])


# ==================== 中间件函数 ====================

def verify_admin_permission(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    db: Session = Depends(get_db)
) -> User:
    """
    管理员权限验证中间件
    
    验证用户token并检查管理员权限：
    - 解析JWT token获取用户信息
    - 验证用户存在且未被删除
    - 检查用户role是否为0（管理员）
    - 如果验证失败，抛出HTTPException或重定向
    
    Args:
        credentials: JWT认证凭据
        db: 数据库会话
    
    Returns:
        User: 验证通过的管理员用户对象
    
    Raises:
        HTTPException: 当token无效、用户不存在或权限不足时抛出异常
    """
    try:
        # 使用auth.py中的verify_token函数解析JWT token
        from utils.auth import verify_token
        payload = verify_token(credentials.credentials)
        user_id_str = payload.get("sub")
        
        if not user_id_str:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Token中缺少用户ID"
            )
        
        try:
            user_id = int(user_id_str)
        except (ValueError, TypeError):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户ID格式错误"
            )
        
        # 查询用户信息
        user = db.query(User).filter(
            User.id == user_id,
            User.is_delete == False
        ).first()
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在或已被删除"
            )
        
        # 检查用户角色，只有管理员（role == 0）才能访问
        if user.role != 0:
            raise HTTPException(
                status_code=status.HTTP_401_FORBIDDEN,
                detail="权限不足，需要管理员权限"
            )
        
        return user
        
    except HTTPException:
        # 重新抛出HTTPException
        raise
    except Exception as e:
        # 其他异常统一处理为401
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Token验证失败"
        )


# ==================== 路由函数定义 ====================

@router.post("/users", summary="创建用户")
async def create_user(
    user_data: UserCreate, 
    db: Session = Depends(get_db),
    admin_user: User = Depends(verify_admin_permission)
):
    """
    创建用户接口
    
    Args:
        user_data: 用户创建数据
        db: 数据库会话
    
    Returns:
        SingleUserResponse: 创建结果响应
    
    Raises:
        HTTPException: 当数据验证失败或创建失败时抛出异常
    """
    try:
        # 验证至少提供用户名、手机号或邮箱中的一个
        if not any([user_data.username, user_data.phone, user_data.email]):
            return {
                "code": 400,
                "msg": "用户名、手机号、邮箱至少需要提供一个"
            }
        
        # 检查用户名是否已存在
        if user_data.username:
            existing_user = db.query(User).filter(
                User.username == user_data.username,
                User.is_delete == False
            ).first()
            if existing_user:
                return {
                    "code": 400,
                    "msg": "用户名已存在"
                }
        
        # 检查手机号是否已存在
        if user_data.phone:
            existing_phone = db.query(User).filter(
                User.phone == user_data.phone,
                User.is_delete == False
            ).first()
            if existing_phone:
                return {
                    "code": 400,
                    "msg": "手机号已存在"
                }
        
        # 检查邮箱是否已存在
        if user_data.email:
            existing_email = db.query(User).filter(
                User.email == user_data.email,
                User.is_delete == False
            ).first()
            if existing_email:
                return {
                    "code": 400,
                    "msg": "邮箱已存在"
                }
        
        # 创建新用户
        # 处理空字符串字段，转换为None以避免数据库唯一索引冲突
        username = user_data.username if user_data.username and user_data.username.strip() else None
        phone = user_data.phone if user_data.phone and user_data.phone.strip() else None
        email = user_data.email if user_data.email and user_data.email.strip() else None
        avatar = user_data.avatar if user_data.avatar and user_data.avatar.strip() else None
        
        new_user = User(
            username=username,
            password=get_password_hash(user_data.password) if user_data.password else None,
            nickname=user_data.nickname,
            avatar=avatar,
            phone=phone,
            email=email,
            gender=user_data.gender or 0,
            birthday=user_data.birthday,
            role=user_data.role or 1,
            create_time=datetime.now(),
            is_delete=False
        )
        
        db.add(new_user)
        db.commit()
        db.refresh(new_user)
        
        # 手动处理数据转换
        user_data = {
            'id': new_user.id,
            'username': new_user.username,
            'nickname': new_user.nickname,
            'avatar': new_user.avatar,
            'gender': new_user.gender if new_user.gender is not None else None,
            'age': new_user.age if new_user.age is not None else None,
            'country': new_user.country,
            'province': new_user.province,
            'city': new_user.city,
            'district': new_user.district,
            'address': new_user.address,
            'role': new_user.role if new_user.role is not None else None,
            'birthday': new_user.birthday if new_user.birthday and str(new_user.birthday).strip() != '' else None,
            'signature': new_user.signature,
            'description': new_user.description,
            'phone': new_user.phone,
            'email': new_user.email,
            'wx_id': new_user.wx_id,
            'qq_id': new_user.qq_id,
            'wx_avatar': new_user.wx_avatar,
            'wx_nickname': new_user.wx_nickname,
            'openid': new_user.openid,
            'xhs_id': new_user.xhs_id,
            'dy_id': new_user.dy_id,
            'wb_id': new_user.wb_id,
            'like_num': getattr(new_user, 'like_num', None),
            'comment_num': getattr(new_user, 'comment_num', None),
            'follow_num': getattr(new_user, 'follow_num', None),
            'fans_num': getattr(new_user, 'fans_num', None),
            'video_num': getattr(new_user, 'video_num', None),
            'collect_num': getattr(new_user, 'collect_num', None),
            'login_time': new_user.login_time,
            'create_time': new_user.create_time,
            'update_time': new_user.update_time,
            'is_delete': new_user.is_delete
        }
        
        # 处理时间字段格式化
        if user_data['birthday'] and hasattr(user_data['birthday'], 'isoformat'):
            user_data['birthday'] = user_data['birthday'].isoformat()
        elif user_data['birthday']:
            user_data['birthday'] = str(user_data['birthday'])
        
        if user_data['login_time'] and hasattr(user_data['login_time'], 'isoformat'):
            user_data['login_time'] = user_data['login_time'].isoformat()
        
        if user_data['create_time'] and hasattr(user_data['create_time'], 'isoformat'):
            user_data['create_time'] = user_data['create_time'].isoformat()
        
        if user_data['update_time'] and hasattr(user_data['update_time'], 'isoformat'):
            user_data['update_time'] = user_data['update_time'].isoformat()
        
        return {
            "code": 200,
            "msg": "用户创建成功",
            "data": user_data
        }
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"创建用户失败: {str(e)}"
        }


@router.get("/users", summary="查询用户列表")
async def get_users_list(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    keyword: Optional[str] = Query(None, description="搜索关键词（用户名、昵称、手机号、邮箱）"),
    role: Optional[int] = Query(None, description="用户角色筛选"),
    db: Session = Depends(get_db),
    admin_user: User = Depends(verify_admin_permission)
):
    """
    查询用户列表接口
    
    Args:
        page: 页码，从1开始
        page_size: 每页数量，最大100
        keyword: 搜索关键词，支持用户名、昵称、手机号、邮箱模糊搜索
        role: 用户角色筛选
        db: 数据库会话
    
    Returns:
        UserListResponse: 用户列表响应
    """
    try:
        # 构建查询条件（排除管理员用户）
        query = db.query(User).filter(
            User.is_delete == False,
            User.role != 0  # 排除管理员用户
        )
        
        # 关键词搜索
        if keyword and keyword.strip():
            keyword = keyword.strip()
            query = query.filter(
                or_(
                    User.username.ilike(f"%{keyword}%"),
                    User.nickname.ilike(f"%{keyword}%"),
                    User.phone.ilike(f"%{keyword}%"),
                    User.email.ilike(f"%{keyword}%")
                )
            )
        
        # 角色筛选
        if role is not None:
            query = query.filter(User.role == role)
        
        # 获取总数
        total = query.count()
        
        # 分页查询
        offset = (page - 1) * page_size
        users = query.order_by(User.create_time.desc()).offset(offset).limit(page_size).all()
        
        # 转换为字典格式数据
        user_list = []
        for user in users:
            user_data = {
                'id': user.id,
                'username': user.username,
                'nickname': user.nickname,
                'avatar': user.avatar,
                'gender': user.gender if user.gender is not None else None,
                'age': user.age if user.age is not None else None,
                'points': user.points,
                'country': user.country,
                'province': user.province,
                'city': user.city,
                'district': user.district,
                'address': user.address,
                'role': user.role if user.role is not None else None,
                'birthday': user.birthday.isoformat() if user.birthday and hasattr(user.birthday, 'isoformat') else (str(user.birthday) if user.birthday else None),
                'signature': user.signature,
                'description': user.description,
                'phone': user.phone,
                'email': user.email,
                'wx_id': user.wx_id,
                'qq_id': user.qq_id,
                'wx_avatar': user.wx_avatar,
                'wx_nickname': user.wx_nickname,
                'openid': user.openid,
                'xhs_id': user.xhs_id,
                'dy_id': user.dy_id,
                'wb_id': user.wb_id,
                'like_num': getattr(user, 'like_num', None),
                'comment_num': getattr(user, 'comment_num', None),
                'follow_num': getattr(user, 'follow_num', None),
                'fans_num': getattr(user, 'fans_num', None),
                'video_num': getattr(user, 'video_num', None),
                'collect_num': getattr(user, 'collect_num', None),
                'login_time': user.login_time.strftime('%Y-%m-%d %H:%M:%S') if user.login_time else None,
                'create_time': user.create_time.strftime('%Y-%m-%d %H:%M:%S') if user.create_time else None,
                'update_time': user.update_time.strftime('%Y-%m-%d %H:%M:%S') if user.update_time else None,
                'is_delete': user.is_delete
            }
            user_list.append(user_data)
        
        return {
            "code": 200,
            "msg": "查询成功",
            "data": user_list,
            "total": total,
            "page": page,
            "page_size": page_size
        }
        
    except Exception as e:
        return {
            "code": 500,
            "msg": f"查询用户列表失败: {str(e)}"
        }


@router.get("/users/{user_id}", summary="查询单个用户")
async def get_user_by_id(
    user_id: int, 
    db: Session = Depends(get_db),
    admin_user: User = Depends(verify_admin_permission)
):
    """
    查询单个用户接口
    
    Args:
        user_id: 用户ID
        db: 数据库会话
    
    Returns:
        SingleUserResponse: 单个用户响应
    
    Raises:
        HTTPException: 当用户不存在时抛出404异常
    """
    try:
        # 查询用户
        user = db.query(User).filter(
            User.id == user_id,
            User.is_delete == False
        ).first()
        
        if not user:
            return {
                "code": 404,
                "msg": "用户不存在"
            }
        
        # 手动处理数据转换
        user_data = {
            'id': user.id,
            'username': user.username,
            'nickname': user.nickname,
            'avatar': user.avatar,
            'background_cover': user.background_cover,
            'gender': user.gender if user.gender is not None else None,
            'age': user.age if user.age is not None else None,
            'points': user.points,
            'country': user.country,
            'province': user.province,
            'city': user.city,
            'district': user.district,
            'address': user.address,
            'role': user.role if user.role is not None else None,
            'birthday': user.birthday if user.birthday and str(user.birthday).strip() != '' else None,
            'signature': user.signature,
            'description': user.description,
            'phone': user.phone,
            'email': user.email,
            'wx_id': user.wx_id,
            'qq_id': user.qq_id,
            'wx_avatar': user.wx_avatar,
            'wx_nickname': user.wx_nickname,
            'openid': user.openid,
            'xhs_id': user.xhs_id,
            'dy_id': user.dy_id,
            'wb_id': user.wb_id,
            'like_num': getattr(user, 'like_num', None),
            'comment_num': getattr(user, 'comment_num', None),
            'follow_num': getattr(user, 'follow_num', None),
            'fans_num': getattr(user, 'fans_num', None),
            'video_num': getattr(user, 'video_num', None),
            'collect_num': getattr(user, 'collect_num', None),
            'login_time': user.login_time,
            'create_time': user.create_time,
            'update_time': user.update_time,
            'is_delete': user.is_delete
        }
        
        # 处理时间字段格式化
        if user_data['birthday'] and hasattr(user_data['birthday'], 'isoformat'):
            user_data['birthday'] = user_data['birthday'].isoformat()
        elif user_data['birthday']:
            user_data['birthday'] = str(user_data['birthday'])
        
        if user_data['login_time'] and hasattr(user_data['login_time'], 'isoformat'):
            user_data['login_time'] = user_data['login_time'].isoformat()
        
        if user_data['create_time'] and hasattr(user_data['create_time'], 'isoformat'):
            user_data['create_time'] = user_data['create_time'].isoformat()
        
        if user_data['update_time'] and hasattr(user_data['update_time'], 'isoformat'):
            user_data['update_time'] = user_data['update_time'].isoformat()
        
        return {
            "code": 200,
            "msg": "查询成功",
            "data": user_data
        }
        
    except HTTPException:
        raise
    except Exception as e:
        return {
            "code": 500,
            "msg": f"查询用户失败: {str(e)}"
        }


@router.put("/users/{user_id}", summary="修改用户信息")
async def update_user(
    user_id: int, 
    user_data: UserUpdate, 
    db: Session = Depends(get_db),
    admin_user: User = Depends(verify_admin_permission)
):
    """
    修改用户信息接口
    
    Args:
        user_id: 用户ID
        user_data: 用户更新数据
        db: 数据库会话
    
    Returns:
        SingleUserResponse: 修改结果响应
    
    Raises:
        HTTPException: 当用户不存在或数据冲突时抛出异常
    """
    try:
        # 查询用户是否存在
        user = db.query(User).filter(
            User.id == user_id,
            User.is_delete == False
        ).first()
        
        if not user:
            return {
                "code": 400,
                "msg": "用户不存在"
            }
        
        # 检查用户名是否已被其他用户使用
        if user_data.username is not None and user_data.username != user.username:
            existing_user = db.query(User).filter(
                User.username == user_data.username,
                User.is_delete == False,
                User.id != user_id
            ).first()
            if existing_user:
                return {
                    "code": 400,
                    "msg": "用户名已存在"
                }
        
        # 检查手机号是否已被其他用户使用
        if user_data.phone is not None and user_data.phone != user.phone:
            existing_phone = db.query(User).filter(
                User.phone == user_data.phone,
                User.is_delete == False,
                User.id != user_id
            ).first()
            if existing_phone:
                return {
                    "code": 400,
                    "msg": "手机号已存在"
                }
        
        # 检查邮箱是否已被其他用户使用
        if user_data.email is not None and user_data.email != user.email:
            existing_email = db.query(User).filter(
                User.email == user_data.email,
                User.is_delete == False,
                User.id != user_id
            ).first()
            if existing_email:
                return {
                    "code": 400,
                    "msg": "邮箱已存在"
                }
        
        # 检查微信openid是否已被其他用户使用
        if user_data.openid is not None and user_data.openid != user.openid:
            existing_openid = db.query(User).filter(
                User.openid == user_data.openid,
                User.is_delete == False,
                User.id != user_id
            ).first()
            if existing_openid:
                return {
                    "code": 400,
                    "msg": "微信已绑定用户"
                }
        
        # 检查微信号是否已被其他用户使用
        if user_data.wx_id is not None and user_data.wx_id != user.wx_id:
            existing_wx_id = db.query(User).filter(
                User.wx_id == user_data.wx_id,
                User.is_delete == False,
                User.id != user_id
            ).first()
            if existing_wx_id:
                return {
                    "code": 400,
                    "msg": "微信号已存在"
                }
        
        # 检查QQ号是否已被其他用户使用
        if user_data.qq_id is not None and user_data.qq_id != user.qq_id:
            existing_qq_id = db.query(User).filter(
                User.qq_id == user_data.qq_id,
                User.is_delete == False,
                User.id != user_id
            ).first()
            if existing_qq_id:
                return {
                    "code": 400,
                    "msg": "QQ号已存在"
                }
        
        # 检查小红书ID是否已被其他用户使用
        if user_data.xhs_id is not None and user_data.xhs_id != user.xhs_id:
            existing_xhs_id = db.query(User).filter(
                User.xhs_id == user_data.xhs_id,
                User.is_delete == False,
                User.id != user_id
            ).first()
            if existing_xhs_id:
                return {
                    "code": 400,
                    "msg": "小红书ID已存在"
                }
        
        # 检查抖音ID是否已被其他用户使用
        if user_data.dy_id is not None and user_data.dy_id != user.dy_id:
            existing_dy_id = db.query(User).filter(
                User.dy_id == user_data.dy_id,
                User.is_delete == False,
                User.id != user_id
            ).first()
            if existing_dy_id:
                return {
                    "code": 400,
                    "msg": "抖音ID已存在"
                }
        
        # 检查微博ID是否已被其他用户使用
        if user_data.wb_id is not None and user_data.wb_id != user.wb_id:
            existing_wb_id = db.query(User).filter(
                User.wb_id == user_data.wb_id,
                User.is_delete == False,
                User.id != user_id
            ).first()
            if existing_wb_id:
                return {
                    "code": 400,
                    "msg": "微博ID已存在"
                }
        
        # 更新用户信息（只更新非None的字段）
        update_data = user_data.dict(exclude_unset=True)
        
        # 如果有密码更新，需要加密
        if 'password' in update_data and update_data['password']:
            update_data['password'] = get_password_hash(update_data['password'])
        
        # 更新时间
        update_data['update_time'] = datetime.now()
        
        # 执行更新
        for field, value in update_data.items():
            setattr(user, field, value)
        
        db.commit()
        db.refresh(user)
        
        # 手动处理数据转换
        user_data = {
            'id': user.id,
            'username': user.username,
            'nickname': user.nickname,
            'avatar': user.avatar,
            'gender': user.gender if user.gender is not None else None,
            'age': user.age if user.age is not None else None,
            'points': user.points,
            'country': user.country,
            'province': user.province,
            'city': user.city,
            'district': user.district,
            'address': user.address,
            'role': user.role if user.role is not None else None,
            'birthday': user.birthday if user.birthday and str(user.birthday).strip() != '' else None,
            'signature': user.signature,
            'description': user.description,
            'phone': user.phone,
            'email': user.email,
            'wx_id': user.wx_id,
            'qq_id': user.qq_id,
            'wx_avatar': user.wx_avatar,
            'wx_nickname': user.wx_nickname,
            'openid': user.openid,
            'xhs_id': user.xhs_id,
            'dy_id': user.dy_id,
            'wb_id': user.wb_id,
            'like_num': getattr(user, 'like_num', None),
            'comment_num': getattr(user, 'comment_num', None),
            'follow_num': getattr(user, 'follow_num', None),
            'fans_num': getattr(user, 'fans_num', None),
            'video_num': getattr(user, 'video_num', None),
            'collect_num': getattr(user, 'collect_num', None),
            'login_time': user.login_time,
            'create_time': user.create_time,
            'update_time': user.update_time,
            'is_delete': user.is_delete
        }
        
        # 处理时间字段格式化
        if user_data['birthday'] and hasattr(user_data['birthday'], 'isoformat'):
            user_data['birthday'] = user_data['birthday'].isoformat()
        elif user_data['birthday']:
            user_data['birthday'] = str(user_data['birthday'])
        
        if user_data['login_time'] and hasattr(user_data['login_time'], 'isoformat'):
            user_data['login_time'] = user_data['login_time'].isoformat()
        
        if user_data['create_time'] and hasattr(user_data['create_time'], 'isoformat'):
            user_data['create_time'] = user_data['create_time'].isoformat()
        
        if user_data['update_time'] and hasattr(user_data['update_time'], 'isoformat'):
            user_data['update_time'] = user_data['update_time'].isoformat()
        
        return {
            "code": 200,
            "msg": "用户信息更新成功",
            "data": user_data
        }
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新用户信息失败: {str(e)}"
        )


@router.delete("/users/{user_id}", summary="删除用户")
async def delete_user(
    user_id: int, 
    db: Session = Depends(get_db),
    admin_user: User = Depends(verify_admin_permission)
):
    """
    删除用户接口（软删除）
    
    Args:
        user_id: 用户ID
        db: 数据库会话
    
    Returns:
        dict: 删除结果响应
    
    Raises:
        HTTPException: 当用户不存在时抛出404异常
    """
    try:
        # 查询用户是否存在
        user = db.query(User).filter(
            User.id == user_id,
            User.is_delete == False
        ).first()
        
        if not user:
            return {
                "code": 400,
                "msg": "用户不存在"
            }
     
        # 执行软删除
        user.is_delete = True
        user.update_time = datetime.now()
        
        db.commit()
        
        return {
            "code": 200,
            "msg": "用户删除成功"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除用户失败: {str(e)}"
        )


@router.post("/login", summary="管理员登录")
async def admin_login(
    login_data: AdminLogin, 
    db: Session = Depends(get_db)
):
    """
    管理员登录接口
    只有role=0的用户才能登录管理后台
    只支持用户名密码验证方式
    
    Args:
        login_data: 登录数据，包含用户名和密码
        db: 数据库会话
    
    Returns:
        AdminLoginResponse: 登录响应，包含token和管理员信息
    
    Raises:
        HTTPException: 当用户名密码错误或没有管理员权限时抛出异常
    """
    try:
        # 验证输入参数
        if not login_data.username or not login_data.password:
            return {
                "code": 400,
                "msg": "用户名或密码不能为空"
            }
        # 根据用户名查询用户
        user = db.query(User).filter(
            User.username == login_data.username,
            User.is_delete == False
        ).first()
        
        # 验证用户是否存在
        if not user:
            return{
                "code": 400,
                "msg": "用户名不存在"
            }
        
        # 验证密码
        if not verify_password(login_data.password, user.password):
            return{
                "code": 400,
                "msg": "用户名或密码错误"
            }
        
        # 验证管理员权限 - 只有role=0的用户才是管理员
        if user.role != 0:
            return {
                "code": 1,
                "msg": "你没有权限访问管理后台"
            }

        # 更新登录时间
        user.login_time = datetime.now()
        db.commit()
        
        # 生成访问令牌
        token_data = create_user_token(user.id, user.username or user.nickname)
        
        # 返回登录成功响应
        return {
            "code": 200,
            "msg": "登录成功",
            "access_token": token_data["access_token"],
            "token_type": token_data["token_type"],
            "admin_info": {
                "id": user.id,
                "username": user.username,
                "nickname": user.nickname,
                "avatar": user.avatar or user.wx_avatar,
                "role": user.role,
                "login_time": user.login_time.isoformat() if user.login_time else None
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"登录失败: {str(e)}"
        )


@router.get("/dashboard",summary="管理员登录页面访问接口")
async def login(
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
    db: Session = Depends(get_db)
):
    """
    管理员登录页面访问接口
    
    当通过浏览器直接访问时，会解析token身份：
    - 如果token有效且用户role等于0（管理员），返回登录成功
    - 如果token无效或用户role不等于0，重定向到/home页面
    - 如果没有token，返回登录页面
    
    Args:
        credentials: JWT认证凭据
        db: 数据库会话
    
    Returns:
        dict/RedirectResponse: 登录结果或重定向响应
    """

    # 如果提供了token，尝试解析
    if credentials:
        try:
            # 使用auth.py中的verify_token函数解析JWT token
            from utils.auth import verify_token
            payload = verify_token(credentials.credentials)
            user_id_str = payload.get("sub")
            
            
            if user_id_str:
                try:
                    user_id = int(user_id_str)
                    # 查询用户信息
                    user = db.query(User).filter(
                        User.id == user_id,
                        User.is_delete == False
                    ).first()
                    
                    if user:
                        print(user.username, 11111111111111111111)
                        # 检查用户角色，如果不是管理员（role != 0）则重定向
                        if user.role != 0:
                            return RedirectResponse(url="/home", status_code=401)
                        
                        # 管理员用户，返回登录成功
                        return {
                            "code": 200,
                            "msg": "登录成功",
                            "data": {
                                "user_id": user.id,
                                "username": user.username,
                                "role": user.role,
                                "nickname": user.nickname,
                                "avatar": user.avatar or user.wx_avatar,
                                "login_time": user.login_time.isoformat() if user.login_time else None,
                                "ai_count": 1204,
                                "user_count":12,
                                "today_visit":1204,
                                "ai_click": 3267
                            }
                        }
                except (ValueError, TypeError):
                    # 用户ID格式错误，重定向到首页
                    return RedirectResponse(url="/home", status_code=401)
        except HTTPException:
            # Token无效或过期，重定向到首页
            return RedirectResponse(url="/home", status_code=401)
    
    # 没有token或token解析失败，返回登录页面信息
    return {
        "code": 200,
        "msg": "请登录管理员账号",
    }


@router.post("/admin/reset-password", summary="重置管理员密码")
async def reset_admin_password(
    password_data: AdminResetPassword,
    db: Session = Depends(get_db),
    admin_user: User = Depends(verify_admin_permission)
):
    """
    重置管理员密码接口
    只有role=0的管理员才能重置密码
    需要先验证旧密码，然后才能设置新密码
    
    Args:
        password_data: 密码重置数据，包含旧密码、新密码和确认密码
        db: 数据库会话
        admin_user: 当前管理员用户对象
    
    Returns:
        dict: 重置结果响应
    
    Raises:
        HTTPException: 当用户不存在、没有权限、旧密码错误或重置失败时抛出异常
    """
    try:
        # 获取当前管理员用户
        user = admin_user
        
        # 验证用户是否存在
        if not user:
            return {
                "code": 400,
                "msg": "用户不存在"
            }

        
        # 验证管理员权限 - 只有role=0的用户才是管理员
        if user.role != 0:
            return {
                "code": 400,
                "msg": "你没有权限重置管理员密码",
            }
        # 验证旧密码是否正确
        if not verify_password(password_data.old_password, user.password):
            return {
                "code": 400,
                "msg": "旧密码输入错误",
            }
        
        # 检查新密码是否与旧密码相同
        if verify_password(password_data.new_password, user.password):
            return {
                "code": 400,
                "msg": "新密码不能与当前密码相同",

            }
        
        # 更新密码
        user.password = get_password_hash(password_data.new_password)
        user.update_time = datetime.now()
        
        db.commit()
        
        return {
            "code": 200,
            "msg": "管理员密码重置成功",
        }
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"重置密码失败: {str(e)}"
        )



# 修改管理员的账号信息
@router.put("/admin/info", summary="修改管理员账号信息")
async def update_admin_info(
    admin_update: AdminInfoUpdate,
    db: Session = Depends(get_db),
    admin_user: User = Depends(verify_admin_permission)
):
    """
    修改管理员账号信息接口
    只有role=0的管理员才能修改自己的账号信息
    不允许修改密码和角色，这些需要通过专门的接口
    
    Args:
        admin_update: 管理员信息更新数据
        db: 数据库会话
        admin_user: 当前管理员用户对象
    
    Returns:
        AdminInfoUpdateResponse: 更新结果响应
    
    Raises:
        HTTPException: 当用户不存在、没有权限或更新失败时抛出异常
    """
    try:
        # 获取当前管理员用户
        user = admin_user
        
        # 验证用户是否存在
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )
        
        # 验证管理员权限 - 只有role=0的用户才是管理员
        if user.role != 0:
            raise HTTPException(
                status_code=status.HTTP_401_FORBIDDEN,
                detail="你没有权限修改管理员信息"
            )
        
        # 检查用户名是否已被其他用户使用
        if admin_update.username and admin_update.username != user.username:
            existing_user = db.query(User).filter(
                User.username == admin_update.username,
                User.id != user.id,
                User.is_delete == False
            ).first()
            if existing_user:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="用户名已被其他用户使用"
                )
        
        # 检查手机号是否已被其他用户使用
        if admin_update.phone and admin_update.phone != user.phone:
            existing_phone = db.query(User).filter(
                User.phone == admin_update.phone,
                User.id != user.id,
                User.is_delete == False
            ).first()
            if existing_phone:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="手机号已被其他用户使用"
                )
        
        # 检查邮箱是否已被其他用户使用
        if admin_update.email and admin_update.email != user.email:
            existing_email = db.query(User).filter(
                User.email == admin_update.email,
                User.id != user.id,
                User.is_delete == False
            ).first()
            if existing_email:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="邮箱已被其他用户使用"
                )
        
        # 更新用户信息（只更新提供的字段）
        update_fields = {}
        
        if admin_update.username is not None:
            update_fields['username'] = admin_update.username
        if admin_update.nickname is not None:
            update_fields['nickname'] = admin_update.nickname
        if admin_update.avatar is not None:
            update_fields['avatar'] = admin_update.avatar
        if admin_update.gender is not None:
            update_fields['gender'] = admin_update.gender
        if admin_update.birthday is not None:
            update_fields['birthday'] = admin_update.birthday
        if admin_update.description is not None:
            update_fields['description'] = admin_update.description
        if admin_update.phone is not None:
            update_fields['phone'] = admin_update.phone
        if admin_update.email is not None:
            update_fields['email'] = admin_update.email
        
        # 如果没有要更新的字段，返回提示
        if not update_fields:
            return {
                "code": 400,
                "msg": "没有提供要更新的信息"
            }
        
        # 添加更新时间
        update_fields['update_time'] = datetime.now()
        
        # 执行更新
        for field, value in update_fields.items():
            setattr(user, field, value)
        
        db.commit()
        db.refresh(user)
        
        # 构建返回的用户信息
        user_response = {
            'id': user.id,
            'username': user.username,
            'nickname': user.nickname,
            'avatar': user.avatar,
            'background_cover': user.background_cover,
            'gender': user.gender,
            'age': user.age,
            'points': user.points,
            'country': user.country,
            'province': user.province,
            'city': user.city,
            'district': user.district,
            'address': user.address,
            'role': user.role,
            'birthday': user.birthday.isoformat() if user.birthday else None,
            'signature': user.signature,
            'description': user.description,
            'phone': user.phone,
            'email': user.email,
            'wx_id': user.wx_id,
            'qq_id': user.qq_id,
            'wx_avatar': user.wx_avatar,
            'wx_nickname': user.wx_nickname,
            'openid': user.openid,
            'xhs_id': user.xhs_id,
            'dy_id': user.dy_id,
            'wb_id': user.wb_id,
            'like_num': getattr(user, 'like_num', None),
            'comment_num': getattr(user, 'comment_num', None),
            'follow_num': getattr(user, 'follow_num', None),
            'fans_num': getattr(user, 'fans_num', None),
            'video_num': getattr(user, 'video_num', None),
            'collect_num': getattr(user, 'collect_num', None),
            'login_time': user.login_time.isoformat() if user.login_time else None,
            'create_time': user.create_time.isoformat() if user.create_time else None,
            'update_time': user.update_time.isoformat() if user.update_time else None,
            'is_delete': user.is_delete
        }
        
        return {
            "code": 200,
            "msg": "管理员信息更新成功",
            "data": user_response
        }
        
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新管理员信息失败: {str(e)}"
        )


# ======================
# 获取工具列表
@router.get("/tools_list", summary="获取工具列表")
async def get_tools_list(
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    category: Optional[str] = Query(None, description="分类名称"),
    is_active: Optional[bool] = Query(None, description="是否启用"),
    upload_by: Optional[str] = Query(None, description="系统上传为system"),
    pageNum: Optional[int] = Query(1, description="页码，默认为1"),
    pageSize: Optional[int] = Query(10, description="每页数量，默认为10"),
    db: Session = Depends(get_db)
):
    """
    获取工具列表（带分页）
    根据关键词查询active=1未禁用的AI工具，返回扁平化的工具数组
    
    分页功能说明：
    - pageNum: 页码，默认为1
    - pageSize: 每页数量，默认为10
    """
    try:
        # 构建基础查询条件 - 联表查询获取分类排序信息
        query = db.query(Tools, Tools_type.sort_order).join(
            Tools_type, Tools.category == Tools_type.name
        ).filter(
            Tools_type.is_active == True  # 分类必须启用
        )
        
        # 是否启用过滤
        if is_active is not None:
            query = query.filter(Tools.is_active == (1 if is_active else 0))
        else:
            # 默认只查询启用的工具
            query = query.filter(Tools.is_active == 1)
        
        # 分类过滤
        if category:
            category = category.strip()
            if category:
                query = query.filter(Tools.category.ilike(f"%{category}%"))
        
        # 上传者过滤（系统上传为system）
        if upload_by is not None:
            upload_by = upload_by.strip()
            if upload_by == "system":
                # 系统上传的工具（upload_by为0）
                query = query.filter(Tools.upload_by == "0")
            elif upload_by and upload_by != "system":
                # 用户上传的工具（upload_by不为0）
                query = query.filter(Tools.upload_by != "0")
        
        # 关键词搜索 - 优化搜索逻辑
        if keyword:
            # 去除关键词前后空格并转换为小写进行模糊搜索
            keyword = keyword.strip()
            if keyword:  # 确保关键词不为空
                search_filter = or_(
                    Tools.title.ilike(f"%{keyword}%"),  # 不区分大小写的模糊搜索
                    Tools.description.ilike(f"%{keyword}%"),
                    Tools.category.ilike(f"%{keyword}%"),  # 添加分类字段搜索
                    Tools_type.name.ilike(f"%{keyword}%")  # 添加分类名称搜索
                )
                query = query.filter(search_filter)
        
        # 按分类排序字段和工具排序字段排序
        query = query.order_by(Tools_type.sort_order.asc(), Tools.sort_order.asc())
        
        # 获取符合条件的工具总数
        total_count = query.count()
        
        # 分页处理
        offset = (pageNum - 1) * pageSize
        query = query.offset(offset).limit(pageSize)
        
        # 获取工具数据
        results = query.all()
        
        # 转换为扁平化的工具数组，并添加上传人信息
        tools_list = []
        for tool, category_sort_order in results:
            # 转换工具数据
            tool_data = ToolsResponse.from_orm(tool).dict()
            
            # 处理上传人信息
            if tool.upload_by == 0:
                tool_data["uploader_name"] = "system"
            else:
                # 查询用户信息
                try:
                    user_id = int(tool.upload_by)
                    user = db.query(User).filter(User.id == user_id, User.is_delete == False).first()
                    if user:
                        tool_data["uploader_name"] = user.username or user.nickname or f"用户{user_id}"
                    else:
                        tool_data["uploader_name"] = f"未知用户({tool.upload_by})"
                except (ValueError, TypeError):
                    tool_data["uploader_name"] = f"未知用户({tool.upload_by})"
            
            tools_list.append(tool_data)
        
        return {
            "code": 200,
            "msg": "获取工具列表成功",
            "data": {
                "total": total_count,
                "pageNum": pageNum,
                "pageSize": pageSize,
                "totalPages": max(1, (total_count + pageSize - 1) // pageSize),  # 向上取整计算总页数
                "tools": tools_list
            }
        }
    
    except Exception as e:
        return {
            "code": 500,
            "msg": f"获取工具列表失败: {str(e)}"
        }


# =========== 审核作品 ================




# ============ 首页banner =============

@router.get("/banners", summary="获取轮播图列表")
async def get_banners(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    is_active: Optional[bool] = Query(None, description="是否启用"),
    db: Session = Depends(get_db)
):
    """
    获取轮播图列表
    """
    try:
        # 构建查询条件
        query = db.query(Banner).filter(Banner.is_delete == False)
        
        # 只返回启用时间小于等于当前时间的轮播图
        current_time = datetime.now()
        query = query.filter(Banner.enable_time <= current_time)
        
        if is_active is not None:
            query = query.filter(Banner.is_active == is_active)
        
        # 获取总数
        total = query.count()
        
        # 分页查询
        banners = query.order_by(Banner.sort_order.asc(), Banner.create_time.desc()).offset((page - 1) * page_size).limit(page_size).all()
        
        return {
            "code": 200,
            "msg": "获取轮播图列表成功",
            "data": [BannerResponse.from_orm(banner) for banner in banners],
            "total": total,
            "page": page,
            "page_size": page_size
        }
    except Exception as e:
        return {
            "code": 500,
            "msg": f"获取轮播图列表失败: {str(e)}"
        }


@router.post("/banners", summary="创建轮播图")
async def create_banner(
    banner_data: BannerCreate,
    db: Session = Depends(get_db),
    admin_user: User = Depends(verify_admin_permission)
):
    """
    创建新的轮播图
    """
    try:
        # 创建轮播图对象
        new_banner = Banner(
            title=banner_data.title,
            image_url=banner_data.image_url,
            link_url=banner_data.link_url,
            description=banner_data.description,
            sort_order=banner_data.sort_order,
            is_active=banner_data.is_active,
            enable_time=banner_data.enable_time or datetime.now()
        )
        
        db.add(new_banner)
        db.commit()
        db.refresh(new_banner)
        
        return {
            "code": 200,
            "msg": "创建轮播图成功",
            "data": BannerResponse.from_orm(new_banner)
        }
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"创建轮播图失败: {str(e)}"
        }


@router.get("/banners/{banner_id}", summary="获取单个轮播图")
async def get_banner(
    banner_id: int,
    db: Session = Depends(get_db),
    admin_user: User = Depends(verify_admin_permission)
):
    """
    根据ID获取单个轮播图
    """
    try:
        banner = db.query(Banner).filter(Banner.id == banner_id, Banner.is_delete == False).first()
        
        if not banner:
            return {
                "code": 404,
                "msg": "轮播图不存在"
            }
        
        return {
            "code": 200,
            "msg": "获取轮播图成功",
            "data": BannerResponse.from_orm(banner)
        }
    except Exception as e:
        return {
            "code": 500,
            "msg": f"获取轮播图失败: {str(e)}"
        }


@router.put("/banners/{banner_id}", summary="更新轮播图")
async def update_banner(
    banner_id: int,
    banner_data: BannerUpdate,
    db: Session = Depends(get_db),
    admin_user: User = Depends(verify_admin_permission)
):
    """
    更新轮播图信息
    """
    try:
        banner = db.query(Banner).filter(Banner.id == banner_id, Banner.is_delete == False).first()
        
        if not banner:
            return {
                "code": 404,
                "msg": "轮播图不存在"
            }
        
        # 更新字段
        update_data = banner_data.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(banner, field, value)
        
        banner.update_time = datetime.now()
        db.commit()
        db.refresh(banner)
        
        return {
            "code": 200,
            "msg": "更新轮播图成功",
            "data": BannerResponse.from_orm(banner)
        }
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"更新轮播图失败: {str(e)}"
        }


@router.delete("/banners/{banner_id}", summary="删除轮播图")
async def delete_banner(
    banner_id: int,
    db: Session = Depends(get_db),
    admin_user: User = Depends(verify_admin_permission)
):
    """
    软删除轮播图
    """
    try:
        banner = db.query(Banner).filter(Banner.id == banner_id, Banner.is_delete == False).first()
        
        if not banner:
            return {
                "code": 404,
                "msg": "轮播图不存在"
            }
        
        # 软删除
        banner.is_delete = True
        banner.delete_time = datetime.now()
        db.commit()
        
        return {
            "code": 200,
            "msg": "删除轮播图成功"
        }
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"删除轮播图失败: {str(e)}"
        }


@router.patch("/banners/{banner_id}/status", summary="更新轮播图状态")
async def update_banner_status(
    banner_id: int,
    status_data: BannerStatusUpdate,
    db: Session = Depends(get_db),
    admin_user: User = Depends(verify_admin_permission)
):
    """
    更新轮播图启用/禁用状态
    """
    try:
        banner = db.query(Banner).filter(Banner.id == banner_id, Banner.is_delete == False).first()
        
        if not banner:
            return {
                "code": 404,
                "msg": "轮播图不存在"
            }
        
        banner.is_active = status_data.is_active
        banner.update_time = datetime.now()
        db.commit()
        
        status_text = "启用" if status_data.is_active else "禁用"
        return {
            "code": 200,
            "msg": f"轮播图{status_text}成功"
        }
    except Exception as e:
        db.rollback()
        return {
            "code": 500,
            "msg": f"更新轮播图状态失败: {str(e)}"
        }